<template>
  <div class="app-container" v-loading="loading" style="padding: 10px;">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型id" prop="modelId">
        <el-select v-model="queryParams.modelId" placeholder="请选择模型名称" clearable>
          <el-option v-for="dict in model3Dict" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeCreateTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            :shortcuts="shortcuts"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="10" class="mb8">

    </el-row>
<!--    <el-row :gutter="20">-->
      <el-col  :span="22" style="padding-left: 10px">
        <el-row :gutter="20">
          <div id="hisChartDiv" style="width: 100%; height: calc(60vh - 200px);"></div>
        </el-row>
        <el-divider />
        <el-row :gutter="20" v-loading="detailLoading">
          <div id="detailChartDiv" style="width: 100%; height: calc(60vh - 250px);"></div>
        </el-row>

      </el-col>
<!--    </el-row>-->
  </div>
</template>

<script setup name="Model3HisLine">
import { hisChartLine } from "@/api/ba/baModel3His";
import { detailChartLine } from "@/api/ba/baModel3Detail";

import {model3DictList} from '@/utils/baCommon'
import * as echarts from "echarts";
const { model3Dict } =  model3DictList()

const { proxy } = getCurrentInstance();

const showSearch = ref(true);
const loading = ref(false);
const detailLoading = ref(false);
const daterangeCreateTime = ref([]);
const shortcuts = [
  {
    text: '近三天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
      return [start, end]
    },
  },
  {
    text: '近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
]

const data = reactive({
  form: {},
  queryParams: {
    modelId: undefined
  }
})

const { queryParams, form } = toRefs(data);

const props = defineProps({
  params1: {
    type: Object,
    required: false,
    default: {

    }
  }
})

let hisList = undefined
let detailList = undefined

let hisChart = undefined
let detailChart = undefined

function getList(){

}

function handleQuery(){
  queryParams.value.params = {};
  if (!queryParams.value.modelId || queryParams.value.modelId == '') {
    proxy.$modal.alertError("请选择模型名称");
  }
  if (null != daterangeCreateTime ) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];

    loading.value = true;
    try {
      hisChartLine(queryParams.value).then(response => {
        if (response.code === 200) {
          hisList = response.data
          let tmpList = [], xData = []
          if (hisList && hisList.length > 0) {
            hisList.forEach(item => {
              xData.push(item.dt)
              tmpList.push(item.def)
            })
          }
          let option = getHisChartOption(tmpList, xData)
          if (hisChart) {
            hisChart.dispose()
          }
          let hisChartDiv = document.getElementById('hisChartDiv')
          if (hisChartDiv.oncontextmenu) {
            hisChartDiv.oncontextmenu = () => {
              return false
            } //屏蔽右键默认事件
          }
          hisChart = echarts.init(hisChartDiv, 'dark');
          hisChart.setOption(option)
          //点击x轴线
          hisChart.getZr().on('dblclick', params => {
            handleHisChartDivDbClick(params)
          })
        }
      })
    }catch (e){
      proxy.$modal.alertError("查询异常！");
    } finally {
      loading.value = false;
    }

  } else {
    proxy.$modal.alertError("请选择日期范围");
  }
}

function handleHisChartDivDbClick(params) {
  let distance = ""
  const pointInPixel = [params.offsetX, params.offsetY]
  if (hisChart.containPixel('grid', pointInPixel)) {
    const xIndex = hisChart.convertFromPixel({seriesIndex: 0}, [params.offsetX, params.offsetY])[0]
    let option = hisChart.getOption()
    console.log(`xIndex:${xIndex}`)
    console.log(option.xAxis[0].data[xIndex])
    let hisData = hisList[xIndex]
    console.log(`hisData:${JSON.stringify(hisData)}`)
    if (hisData && hisData.id) {
      initDetailChart(hisData.id)
    }
  }
}

function initHisChart() {

}

function resetQuery(){
  proxy.resetForm("queryRef");

}

function getHisChartOption(list, xData) {
  return {
    title: {
      // text: 'Temperature Change in the Coming Week'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {},
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      smooth: true,
      boundaryGap: false,
      data: xData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    dataZoom: [
      {
        type: 'slider',
        xAxisIndex: [0]
      },
      {
        type: 'inside',
        xAxisIndex: [0]
      },
      {
        type: 'slider',
        yAxisIndex:[0],
        left: '95%'
      }
    ],
    series: [
      {
        name: '最大挠度',
        type: 'line',
        data: list,
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
      }
    ]
  };
}

function initDetailChart(hisId) {
  try {
    detailLoading.value = true;
    detailChartLine(hisId).then(response => {
      if (response.code === 200) {
        detailList = response.data
        let xData = [], lista = [], listb = [], listc = [], listd = []
        if (detailList && detailList.length > 0) {
          detailList.forEach(item => {
            xData.push(item.x)
            lista.push(item.a)
            listb.push(item.b)
            listc.push(item.c)
            listd.push(item.d)
          })
        }
        let option = getDetailChartOption(xData, lista, listb, listc, listd)
        if (detailChart) {
          detailChart.dispose()
        }
        let detailChartDiv = document.getElementById('detailChartDiv')
        if (detailChartDiv.oncontextmenu) {
          detailChartDiv.oncontextmenu = () => {
            return false
          } //屏蔽右键默认事件
        }
        detailChart = echarts.init(detailChartDiv, 'dark');
        detailChart.setOption(option)
      }
    })
  }catch (e) {

  } finally {
    detailLoading.value = false;
  }
}

// 初始化 崩岸模型3 明细折线图 y轴
function initDetailChartSeries(lista, listb, listc, listd) {
  let series = [];
  if (lista && lista.length > 0) {
    series.push({
      name: '挠度',
      type: 'line',
      data: lista,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
    })
  }
  if (listb && listb.length > 0) {
    series.push({
      name: '轴向应力',
      type: 'line',
      data: listb,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
    })
  }
  if (listc && listc.length > 0) {
    series.push({
      name: '弯曲应力',
      type: 'line',
      data: listc,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
    })
  }

  if (listd && listd.length > 0) {
    series.push({
      name: '轴向附加应力',
      type: 'line',
      data: listd,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
    })
  }
  return series;
}

function getDetailChartOption(xData, lista, listb, listc, listd) {
  let series = initDetailChartSeries(lista, listb, listc, listd)

  return {
    title: {
      // text: 'Temperature Change in the Coming Week'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {},
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      smooth: true,
      boundaryGap: false,
      data: xData,
      axisLabel: {
        formatter: '{value} m'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    dataZoom: [
      {
        type: 'slider',
        xAxisIndex: [0]
      },
      {
        type: 'inside',
        xAxisIndex: [0]
      },
      {
        type: 'slider',
        yAxisIndex:[0],
        left: '95%'
      }
    ],
    series: series
  };
}

function init() {

}

defineExpose({
  init
})
</script>
